<template>
   <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <el-form :inline="true" label-position="right" size="mini">
       <el-form-item label="学科："   size="mini">
       <el-select  v-model="subjectId" placeholder="请选择学科"   size="mini">
                  <el-option
                    v-for="item in subjectOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
         </el-select>
     </el-form-item>
      <el-form-item label="阶段"  size="mini">
      
          <el-cascader v-model="level"
                    :options="levelOptions"
                    size="mini"
                    :props="levelprops"
                    collapse-tags
                    ></el-cascader>
     </el-form-item>
         <el-button
       
        @click="searchSource()"
        size="mini">
        查询
      </el-button>
      <el-button
        class="btn-add"
        @click="showAddDialog()"
        size="mini">
        添加
      </el-button>
     </el-form>

    </el-card>
    <el-dialog>
    </el-dialog>
    <div class="table-container">
      <el-table ref="productCateTable"
                style="width: 100%"
                :data="sourceOptions"
                 border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.$index+1}}</template>
        </el-table-column>
        <el-table-column label="题目来源" align="center">
          <template slot-scope="scope">{{scope.row.label}}</template>
        </el-table-column>
       
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="showUpdateDialog(scope.row)">编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog title="添加题目来源" :visible.sync="addFormVisible" :close-on-click-modal='false'>
   
	  <el-form :model="addForm" ref="addFormRef" :rules="addFormRule">
	    <el-form-item label="题目来源名称" label-width="`120px`" prop="name" size="mini">
	      <el-input v-model="addForm.name" autocomplete="off"></el-input>
	    </el-form-item>

	    <el-form-item label="学科："   size="mini" prop="subjectId">
       <el-select  v-model="addForm.subjectId" placeholder="请选择学科"    >
                  <el-option
                    v-for="item in subjectOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
         </el-select>
     </el-form-item>
      <el-form-item label="阶段："  size="mini" prop="level">
      
          <el-cascader v-model="addForm.level"
                    :options="levelOptions"
                    size="mini"
                    :props="levelprops"
                    collapse-tags
                    clearable></el-cascader>
     </el-form-item>


	    <el-form-item label="说明" label-width="`120px`" >
	      <el-input v-model="addForm.comment" autocomplete="off"></el-input>
	    </el-form-item>

	   
	    		
	    
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="addFormVisible = false">取 消</el-button>
	    <el-button type="primary" @click="handleAdd('addFormRef')">确 定</el-button>
	  </div>
  </el-dialog>
    <el-dialog title="修改题目来源" :visible.sync="updateFormVisible" :close-on-click-modal='false'>
	  <el-form :model="updateForm" ref="updateFormRef" :rules="updateFormRule">
	    <el-form-item label="题目来源名称" label-width="`120px`" prop="name" size="mini">
	      <el-input v-model="updateForm.name" autocomplete="off"></el-input>
	    </el-form-item>

	     <el-select  abel="学科："v-model="updateForm.subjectId" placeholder="请选择学科"    size="mini" >
                  <el-option
                    v-for="item in subjectOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
         </el-select>
     </el-form-item>
      <el-form-item label="阶段："  size="mini" prop="level"  >
      
          <el-cascader v-model="updateForm.level"
                    :options="levelOptions"
                    size="mini"
                    :props="levelprops"
                    collapse-tags
                    ></el-cascader>
     </el-form-item>


	    <el-form-item label="说明" label-width="`120px`"  >
	      <el-input v-model="updateForm.comment" autocomplete="off"></el-input>
	    </el-form-item>


	    
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="updateFormVisible = false">取 消</el-button>
	    <el-button type="primary" @click="handleUpdate('updateFormRef')">确 定</el-button>
	  </div>
  </el-dialog>
  </div>
</template>
<script type="text/javascript">
	import {mapGetters} from 'vuex'

	import store from '@/store'
	import {fetchList as fetchSourceList,add as addSource,deletes as deleteSource} from '@/api/source'
	import {update as updateSource,get as getSource} from '@/api/source'

	export default {
	    name: "sourceList",
	    data() {
	      return {

	      

	      	subjectId: null, //当前学科
	      	level:null, //阶段
	        list: null,
	       
	        sourceOptions:[], //该学科下对应的source选项

	         //添加学科对话框相应的数据
	        addFormVisible:false,
	        addForm:{
	        	name:null,
	        	comment:null,
	        	subjectId:null,
	        	level:[],
	        	
	        },
	        addFormRule :{
	          name: [{required: true, message: '请输入题型名称', trigger: 'blur'}],
	          subjectId: [{required: true, message: '请选择对应的学科', trigger: 'blur'}],
	          level: [{required: true, message: '请选择对应的阶段', trigger: 'blur'}],
	        },

	        
	        //修改学科对话框相应的数据
	        updateFormVisible:false,
	        updateForm:{
	        	id:null,
	        	name:null,
	        	comment:null,
	        	subjectId:null,
	        	level:[],
	        	
	        },
	        updateFormRule :{
	          name: [{required: true, message: '请输入题型名称', trigger: 'blur'}],
	          subjectId: [{required: true, message: '请选择对应的学科', trigger: 'blur'}],
	          level: [{required: true, message: '请选择对应的阶段', trigger: 'blur'}],
	          
	        },
	        
	        //阶段状态的选项
        	 levelprops: { multiple: true },

	      }
	    },
	    computed:{
	    	...mapGetters([
	          'subjectOptions',
	          'levelOptions',
	          'allLevelList',
	          
	        ]),

	    	/*
	    	level id 字典
	    	 key=level id
	    	 value=父level  id
	    	*/
	    	levelDic : function(){
	    		var dic=new Array()
	    		let allLevelList=this.allLevelList
	    		for (var i=0;i<allLevelList.length;i++){
	    			dic[allLevelList[i].id]=allLevelList[i].parentId

	    		}
	    		return dic

	    	},
	    	
	     



	    },
	    created:function(){ 
	    
	    	if((this.subjectOptions===null) || (this.subjectOptions.length===0))
	    		 return
	    	this.subjectId=this.subjectOptions[0].value
	    	
	    },
	    methods:{
	    	  searchSource(){
	    	  	if (this.level===null){
	    	  		this.$message({
				                type: 'warning',
				                message: '请选择阶段',
				                duration:1000
				             });
	    	  		return
	    	  	}
	      		/*这里传进来的level是一个二位数组,比如
	      		[
		      		[1,2]
		      		[1,3]
		      		[1,4]
	      		]
				表示所有选择的阶段（以及他们的父阶段），传递到server的参数是最后一层的阶段，用逗号隔开
	      		*/
	      		let levelParams=[]

	    		for (let i = 0; i < this.level.length; i++) {
		            levelParams.push(this.level[i][this.level[i].length-1]);
          		}

	      		fetchSourceList({"subjectId":this.subjectId,"levelIds":levelParams.join(',')}).then(response=>{
		        			
				    this.sourceOptions = [];
			        let allSourceList = response.data.list;
			        if (allSourceList===null) return
			        for (let i = 0; i < allSourceList.length; i++) {
			            this.sourceOptions.push({label: allSourceList[i].name, value: allSourceList[i].id});
			        }
			    			

			    }).catch(error=>{

			    	console.log(error)
			     })


	     },


	    	
	    	

	    	showAddDialog(){
	    		this.addForm.name=''
	    		this.addForm.subjectId=null
	    		this.addForm.comment=null
	    		this.addFormVisible=true
	    	},
	    	handleAdd(formName) {
	    		this.$refs[formName].validate(valid => {
	    			if (valid) {
	    				let params={}
	    				params['name']=this.addForm.name
	    				params['subjectId']=this.addForm.subjectId
	    				params['comment']=this.addForm.comment

	    				let levelParams=[]
			    		let addLevel=this.addForm.level
			    		
			    		for (let i = 0; i < addLevel.length; i++) {
				            levelParams.push(addLevel[i][addLevel[i].length-1]);
		          		}
		          		params['levelIds']=levelParams.join(',')
			    		addSource(params).then(response=>{
			    			
			    			//this.$store.dispatch('GetSourceListAll')
				    		
				    		this.level=this.addForm.level
				    		this.subjectId=this.addForm.subjectId
				    		this.searchSource()
				    		this.$message({
				                type: 'success',
				                message: '添加成功',
				                duration:1000
				             });
				    		this.addFormVisible=false


			    		}).catch(error=>{
			    			 
			    			 this.$message({
				                type: 'error',
				                message: '添加失败',
				                duration:1000
				             });
			    		})
			    		this.addFormVisible=false
			    	}
        		})
		    },

		    /*
	    	输入是LevelID
	    	输出是它的父亲节点，祖父节点...直到 ParentId=0 [],
	    	用于在阶段选择下拉框中选中相应的阶段
	    	*/
	    	getLevelParentPath(levelId){
	    		
	    		var parentsPath=[levelId]
	    		var parentId=this.levelDic[levelId]
	    		while (parentId!=0){
	    			parentsPath.unshift(parentId)
	    			parentId=this.levelDic[parentId]

	    		}
	    		
	    		return parentsPath

	    	},

		    showUpdateDialog(row){
	    		this.updateForm.name=row.label
	    		this.updateForm.id=row.value
	    		
	    		
	    		
	    		getSource({"id":this.updateForm.id}).then(response=>{
		        			this.updateForm.subjectId=response.data.subjectId
		        			this.updateForm.name=response.data.name
		        			this.updateForm.comment=response.data.comment
				    		
				    		let updatelevels= response.data.levelIds.split(',')
	    		
	    		
				    		for (var i=0;i<updatelevels.length;i++){
				    			this.updateForm.level.push(this.getLevelParentPath(updatelevels[i]))
				    		}

					    	
					    	this.updateFormVisible=true
			    			

			    		}).catch(error=>{
			    			
			    			console.log(error)
					    			 
			    			})

	    		

	    	},
	    	handleUpdate(formName) {
        		this.$refs[formName].validate(valid => {
	    			if (valid) {

	    				let params={}
	    				params['id']=this.updateForm.id
	    				params['name']=this.updateForm.name
	    				params['subjectId']=this.updateForm.subjectId
	    				params['comment']=this.updateForm.comment

	    				let levelParams=[]
			    		let addLevel=this.updateForm.level
			    		
			    		for (let i = 0; i < addLevel.length; i++) {
				            levelParams.push(addLevel[i][addLevel[i].length-1]);
		          		}
		          		params['levelIds']=levelParams.join(',')

		        		updateSource(params).then(response=>{
		        			
		        			this.level=this.updateForm.level
				    		this.subjectId=this.updateForm.subjectId
				    		
				    		this.searchSource()
				    		this.updateFormVisible=false
					    	this.$message({
						                type: 'success',
						                message: '更新成功',
						                duration:1000
						             });
			    			

			    		}).catch(error=>{
			    			this.updateFormVisible=false
					    			 this.$message({
						                type: 'error',
						                message: '更新失败',
						                duration:1000
						             });
			    			})
			    	}
			    })
		    },

		    handleDelete( row) {
		        this.$confirm('是否要删除该题目来源？如果删除，将彻底删除所有相关的试题！', '提示', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
		        }).then(() => {
		          	 this.$confirm('再次确认删除该题目来源？', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).then(() => {
				        	deleteSource({"id":row.value}).then(response=>{
					    		this.searchSource()
					    		this.$message({
						                type: 'success',
						                message: '删除成功',
						                duration:1000
						             });

					    	}).catch(() => {
		          				this.$message({
					                type: 'error',
					                message: '删除失败',
					                duration:1000
					            });
		          
		       				});


				        }).catch(() => {
		          				
		          
		       			 });
		          
		        }).catch(() => {
		          	
		          
		        });
		      }
	    }
	    
	}
	
	
</script>